package com.dz.lm.service.product.impl;

import com.dz.lm.common.dto.ProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.dao.log.read.LoginLogDao;
import com.dz.lm.dao.product.read.CommonAreaDao;
import com.dz.lm.dao.product.read.ProductDao;
import com.dz.lm.domain.product.CommonArea;
import com.dz.lm.domain.product.Product;
import com.dz.lm.domain.user.User;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.product.ProductService;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends AbstractService implements ProductService {
	
    @Resource(name = "readCommonAreaDao")
    private CommonAreaDao commonAreaDao;
	
    @Resource(name = "readProductDao")
    private ProductDao productDaoRead;
    
    @Resource(name = "readLoginLogDao")
    private LoginLogDao loginLogDao;
    
    @Resource(name = "writeProductDao")
    private com.dz.lm.dao.product.write.ProductDao productDaoWrite;
    
    @Resource(name = "writeAgentDao")
    private com.dz.lm.dao.agent.write.AgentDao agentDaoWrite;
    
    @Resource(name = "readAgentDao")
    private com.dz.lm.dao.agent.read.AgentDao agentDaoRead;
    
    @Resource(name = "readUserDao")
    private com.dz.lm.dao.user.read.UserDao readUserDao;
    


    public List<Map<String, Object>> qryLocalList() throws ServiceException{
    	List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
    	Map<String, Object> sub = new HashMap<String, Object>();
    	Map<String, Object> city = new HashMap<String, Object>();
    	List<Map<String, Object>> cities = new ArrayList<Map<String, Object>>();
    	try {
//    		List<CommonArea> pList = commonAreaDao.qryProvinceList();
//    		for (CommonArea p : pList) {
//    			sub = new HashMap<String, Object>();
//    			sub.put("pId", p.getId());
//    			sub.put("name", p.getName());
//    			sub.put("cityList", commonAreaDao.qryCityList(sub));
//    			retList.add(sub);
//    		}
    		List<Map<String, Object>> localList = commonAreaDao.qryLocalList();
    		Object pId = null;
    		for (Map<String, Object> p : localList) {
    			if (pId == null) {
    				pId = p.get("pId");
    			}
    			if (!pId.equals(p.get("pId"))) {
    				pId = p.get("pId");
    				sub.put("cityList", cities);
    				retList.add(sub);
    				sub = new HashMap<String, Object>();
    				cities = new ArrayList<Map<String, Object>>();
    			}
    			sub.put("pId", p.get("pId"));
    			sub.put("name", p.get("pName"));
    			city.put("cId", p.get("cId"));
    			city.put("name", p.get("name"));
    			cities.add(city);
    			city = new HashMap<String, Object>();
    		}
		} catch (DaoException e) {
			new ServiceException(e.getCause());
		}
    	return retList;
    }
    
    public Map<String, Object> homeProductList(Map<String, Object> qryParam) throws ServiceException {
    	Map<String, Object> retMap = new HashMap<String, Object>();
    	List<Map<String, Object>> productList = null;
    	Integer count = 0;
    	//计算3分钟之前的时间戳类型的参数(180000为毫秒数)
    	Date day = new Date();
    	long beforeTenMin = day.getTime() - 180000;
    	Timestamp ts = new Timestamp(beforeTenMin);
    	qryParam.put("createTime", ts);
		try {
			//返回数据明细
			productList = productDaoRead.qryProductList(qryParam);
			for (Map<String, Object> product : productList) {
				Timestamp times = (Timestamp) product.get("times");
				product.put("times", DateUtil.getTimes(times));
			}
			//返回数据总条数
			count = productDaoRead.qryProductListCount(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("productList", productList);
		retMap.put("count", count);
    	return retMap;
    }
    
    
    public Map<String, Object> ListProductAndAgent() throws ServiceException {
    	Map<String, Object> retMap = new HashMap<String, Object>();
    	List<Map<String, Object>> productList = null;
    	Integer count = 0;
		retMap.put("productList", productList);
		retMap.put("count", count);
    	return retMap;
    }
    
	public ProductDTO selectByPrimaryKey(Map<String, Object> param) throws ServiceException {
		Product product = new Product();
		ProductDTO dto = new ProductDTO();
		try {
			product = productDaoRead.selectByPrimaryKey(param);
			CommonArea province = commonAreaDao.selectByPrimaryKey(Integer.parseInt(product.getProvince()));
			CommonArea city = new CommonArea();
			if (product.getCity() != null) {
				city = commonAreaDao.selectByPrimaryKey(Integer.parseInt(product.getCity()));
			}
			dto.setProductId(product.getProductId());
			dto.setProductName(product.getProductName());
			dto.setProductType(product.getProductType());
			dto.setInfoType(product.getInfoType());
			dto.setProvince(product.getProvince());
			dto.setCity(product.getCity());
			dto.setArea(product.getArea());
			dto.setLongitude(product.getLongitude());
			dto.setLatitude(product.getLatitude());
			dto.setLabel1(product.getLabel1());
			dto.setLabel2(product.getLabel2());
			dto.setLabel3(product.getLabel3());
			dto.setLabel4(product.getLabel4());
			dto.setLabelDescription(product.getLabelDescription());
			dto.setProductDescription(product.getProductDescription());
			dto.setApplyRequire(product.getApplyRequire());
			dto.setProvideMaterial(product.getProvideMaterial());
			dto.setImage1(product.getImage1());
			dto.setImage2(product.getImage2());
			dto.setImage3(product.getImage3());
			dto.setAgentFlag(product.getAgentFlag());
			dto.setPayType(product.getPayType());
			dto.setPayAmount(product.getPayAmount());
			dto.setPayRate(product.getPayRate());
			dto.setHighLightFlag(product.getHighLightFlag());
			dto.setHighLightTime(product.getHighLightTime());
			dto.setAutoUpdateFlag(product.getAutoUpdateFlag());
			dto.setAutoUpdateTime(product.getAutoUpdateTime());
			User u = product.getCreateUser();
			if (u.getLoginName() == null || "".equals(u.getLoginName())) {
				if (u.getUserName() == null || "".equals(u.getUserName())) {
					u.setLoginName("匿名");
				} else {
					u.setLoginName(u.getUserName().substring(0,1) + "经理");
				}
			}
			dto.setCreateUser(u);
			dto.setCreateTime(product.getCreateTime());
			dto.setUpdateTime(product.getUpdateTime());
			dto.setUpDownFlag(product.getUpDownFlag());
			dto.setTimes(DateUtil.getTimes(product.getUpdateTime()));
			dto.setAddress(province.getName() + " " + (city.getName() != null ? city.getName() : ""));
			dto.setFavoriteFlag(product.getFavoriteFlag());
			dto.setRadiatCityCode(product.getRadiatCityCode());
			dto.setRadiatCityName(product.getRadiatCityName());
			dto.setApplyFlag(product.getApplyFlag());
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		return dto;
	}
    
	@Transactional
    public Map<String, Object> siftingSearch(Map<String, Object> qryParam) throws ServiceException {
    	Map<String, Object> retMap = new HashMap<String, Object>();
    	List<Map<String, Object>> productList = null;
    	Integer count = 0;
    	//计算3分钟之前的时间戳类型的参数(180000为毫秒数)
    	Date day = new Date();
    	long beforeTenMin = day.getTime() - 180000;
    	Timestamp ts = new Timestamp(beforeTenMin);
    	qryParam.put("createTime", ts);
		try {
			//createAgentFlag 0：创建的产品 1：代理的产品
			Object createAgentFlag = qryParam.get("createAgentFlag");
			if (createAgentFlag == null || "".equals(createAgentFlag.toString())) {
				//返回数据明细
				productList = productDaoRead.qryProductList1(qryParam);
				//返回数据总条数
				count = productDaoRead.qryProductListCount1(qryParam);
			} else if ("0".equals(createAgentFlag.toString())) {
				//返回数据明细
				productList = productDaoRead.qryProductList2(qryParam);
				//返回数据总条数
				count = productDaoRead.qryProductListCount2(qryParam);
			} else if ("1".equals(createAgentFlag.toString())) {
				//返回数据明细
				productList = productDaoRead.qryProductList3(qryParam);
				//返回数据总条数
				count = productDaoRead.qryProductListCount3(qryParam);
			}
			for (Map<String, Object> product : productList) {
				Timestamp times = (Timestamp) product.get("times");
				product.put("times", DateUtil.getTimes(times));
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("productList", productList);
		retMap.put("count", count);
    	return retMap;
    }
	
	@Transactional
    public Map<String, Object> agentProductList(Map<String, Object> qryParam) throws ServiceException {
    	Map<String, Object> retMap = new HashMap<String, Object>();
    	List<Map<String, Object>> productList = null;
    	Integer count = 0;
    	//计算3分钟之前的时间戳类型的参数(180000为毫秒数)
    	Date day = new Date();
    	long beforeTenMin = day.getTime();// - 180000;
    	Timestamp ts = new Timestamp(beforeTenMin);
    	qryParam.put("createTime", ts);
		try {
			//返回数据明细
			productList = productDaoRead.agentProductList(qryParam);
			//返回数据总条数
			count = productDaoRead.agentProductListCount(qryParam);
			for (Map<String, Object> product : productList) {
				Timestamp times = (Timestamp) product.get("times");
				product.put("times", DateUtil.getTimes(times));
			}
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
		retMap.put("productList", productList);
		retMap.put("count", count);
    	return retMap;
    }
    
    public List<Map<String, Object>> releasableProducts(Map<String, Object> qryParam) throws ServiceException {
    	List<Map<String, Object>> productList = null;
		try {
			//可发布产品列表
			productList = productDaoRead.qryReleasableProducts(qryParam);
		} catch (DaoException e) {
			throw new ServiceException(e.getCause());
		}
    	return productList;
    }

	
    public List<ProductDTO> listSelectedProducts() {
        List<Product> products = productDaoRead.listSelectedProduct();
        return formatProduct(products);
    }

    public List<ProductDTO> listHotProducts() {
        List<Product> products = productDaoRead.listHotProduct();
        return formatProduct(products);
    }

    public List<ProductDTO> listProducts(byte status) {
        List<Product> products = productDaoRead.listProduct(status, 0, 50);
        return formatProduct(products);
    }
    
    public int addNeeds(Map<String, Object> qryParam) throws ServiceException{
    	return productDaoWrite.insert(qryParam);
    }
    
    public int addProduct(Map<String, Object> qryParam) throws ServiceException{
    	int count = 0;
    	try {
    		count = productDaoWrite.insert(qryParam);
    		if (count == 1) {
    			return Integer.valueOf(productDaoRead.qryMyMaxProductId(qryParam).get("productId").toString());
    		}
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
    }
    
	public int modifyNeeds(Map<String, Object> param) throws ServiceException {
		int count = 0;
		try {
			count = productDaoWrite.modifyProduct(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
	}
	
	public Map<String, Object> qryProductInfoByProductId(Map<String, Object> param) throws ServiceException {
		try {
			return productDaoRead.qryProductInfoByProductId(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return null;
	}
	public int modifyProduct(Map<String, Object> param) throws ServiceException {
		int count = 0;
		try {
			count = productDaoWrite.modifyProduct(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
	}
    
	public Map<String, Object> qryByParentId(Map<String, Object> param) throws ServiceException {
		Map<String, Object> agentProduct = null;
		try {
			agentProduct = productDaoRead.qryAgentProductInfo(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return agentProduct;
	}
	
	public Map<String, Object> qryAgentProduct(Map<String, Object> param) throws ServiceException {
		Map<String, Object> agentProduct = null;
		try {
			agentProduct = productDaoRead.qryAgentProduct(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return agentProduct;
	}
	
	public Map<String, Object> qryByParentId(Integer productId) throws ServiceException {
		Map<String, Object> agentProduct = null;
		try {
			agentProduct = productDaoRead.qryAgentProductInfoByProductId(productId);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return agentProduct;
	}
	@Transactional
	public Map<String, Object> applyProductAgent(Map<String, Object> param) throws ServiceException {
		Map<String, Object> retData = new HashMap<String, Object>();
		int count = 0;
		String state = "0";
		try {
			Map<String, Object> agent = null;
			if ("1".equals(param.get("agentClass"))) {
				agent = agentDaoRead.qryAgentInfoByUserIdToBarId(param);
			} else {
				agent = agentDaoRead.qryAgentInfoByUserId(param);
			}
			if (agent == null || agent.isEmpty()) {
				count = agentDaoWrite.addAgent(param);
			} else if (!"1".equals(agent.get("state"))) {
				param.put("state", "0");
	    		if (param.get("pUserId") == null || "".equals(param.get("pUserId").toString())) {
	    			param.put("pUserId", 0);
	    		}
	    		if ("1".equals(param.get("agentClass"))) {
					count = agentDaoWrite.updateAgent(param);
	    		} else {
					count = agentDaoWrite.updateAgent2(param);
	    		}
			} else {
				param.put("state", "1");
				state = "1";
			}
			count = productDaoWrite.applyProductAgent(param);
			retData.put("count", count);
			retData.put("state", state);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return retData;
	}
	@Transactional
	public int updateAgentProduct(Map<String, Object> param) throws ServiceException {
		int count = 0;
		try {
			count = productDaoWrite.updateAgentProduct(param);
		} catch (DaoException e) {
			e.printStackTrace();
		}
    	return count;
	}
    
    private List<ProductDTO> formatProduct(List<Product> products) {
        List<ProductDTO> dtoList = new ArrayList(products.size());
        for (Product product : products) {
            ProductDTO dto = new ProductDTO();
            dtoList.add(dto);
        }
        return dtoList;
    }
}
